package com.itheima.tlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias.exception.BusinessException;
import com.itheima.tlias.mapper.ClazzMapper;
import com.itheima.tlias.mapper.StudentMapper;
import com.itheima.tlias.pojo.*;
import com.itheima.tlias.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author mr.luo
 * @Date 05 4月 2025 19:27
 */
@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    /**
     * 查询所有班级信息
     *
     * @return
     */
    @Override
    public PageResult findAll(ClazzsDTO clazzsDTO) {
        //使用pageHelper分页插件查询所有班级信息
        PageHelper.startPage(clazzsDTO.getPage(), clazzsDTO.getPageSize());
        Page<ClazzVO> page = clazzMapper.pageQuery(clazzsDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据id删除班级信息
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        //查询该班级下的所有学生信息
        List<StudentVo> students = studentMapper.selectByClazzId(id);
        if (!students.isEmpty()) {
            throw new BusinessException("该班级下有学生，不能删除"); // 400 表示业务错误
        }
        // 删除班级信息
        clazzMapper.delete(id);
    }

    /**
     * 添加班级信息
     *
     * @param addClazzsDTO
     */
    @Override
    public void add(AddClazzsDTO addClazzsDTO) {
        addClazzsDTO.setCreateTime(LocalDateTime.now());
        addClazzsDTO.setUpdateTime(LocalDateTime.now());
        clazzMapper.add(addClazzsDTO);
    }

    /**
     * 根据id查询班级信息
     *
     * @param id
     * @return
     */
    @Override
    public ClazzVO findById(Integer id) {
        return clazzMapper.findById(id);
    }

    /**
     * 修改班级信息
     *
     * @param clazzVO
     */
    @Override
    public void update(ClazzVO clazzVO) {
        clazzVO.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazzVO);
    }

    /**
     * 查询所有班级信息
     */
    @Override
    public List<ClazzVO> findAllClass() {
        return clazzMapper.findAllClass();
    }
}
